#version 330

in vec2 fragTexCoord;
in vec3 fragPosition;
in vec3 fragNormal;

uniform sampler2D texture0;
uniform vec4 colDiffuse;
uniform float intensity;
uniform vec4 direction; // 正交方向
uniform vec4 diagDirection; // 对角线方向
uniform float me;

out vec4 finalColor;

// 计算到最近墙的距离
float distanceToWall(vec2 texCoord, vec4 ortho, vec4 diag)
{
    float minDistance = 1.0;
    
    // 检查正交方向
    if(ortho.x > 0.5) minDistance = min(minDistance, texCoord.x); // 左
    if(ortho.y > 0.5) minDistance = min(minDistance, 1.0 - texCoord.x); // 右
    if(ortho.z > 0.5) minDistance = min(minDistance, 1.0 - texCoord.y); // 上
    if(ortho.w > 0.5) minDistance = min(minDistance, texCoord.y); // 下
    
    // 检查对角线方向
    // 检查对角线方向
    if(diag.x > 0.5) minDistance = min(minDistance, length(vec2(texCoord.x, 1.0 - texCoord.y))); // 右下
    if(diag.y > 0.5) minDistance = min(minDistance, length(vec2(1.0 - texCoord.x, 1.0 - texCoord.y))); // 右下
    if(diag.z > 0.5) minDistance = min(minDistance, length(texCoord)); // 右上
    if(diag.w > 0.5) minDistance = min(minDistance, length(vec2(1.0 - texCoord.x, texCoord.y))); // 左上
    
    return minDistance;
}

void main()
{
    vec3 baseColor = vec3(1.,1.,1.);
    
    // 如果不是墙，使用基础颜色
    if (me > 0.5) {
        finalColor = vec4(baseColor, 1.);
        return;
    }

    // 计算到最近墙的距离
    float distance = distanceToWall(fragTexCoord, direction, diagDirection);
    
    // 如果没有相邻的墙，使用基础颜色
    if(distance >= 0.99) {
        finalColor = vec4(baseColor, 1.);
        return;
    }
    
    float shadowIntensity = (intensity > 0.0) ? intensity : 0.5;
    
    // 使用距离计算阴影因子
    // 距离越近，阴影越深
    float shadowFactor = mix(1.0 - shadowIntensity, 1.0, 
                            smoothstep(0.0, 0.3, distance));
    
    // 对于尖角情况，使用更陡的过渡
    if(distance < 0.3) {
        shadowFactor = mix(1.0 - shadowIntensity * 1.2, shadowFactor, 
                          smoothstep(0.0, 0.1, distance));
    }
    
    shadowFactor = max(shadowFactor, 0.3);
    
    vec3 finalColorRGB = baseColor * shadowFactor;
    finalColor = vec4(finalColorRGB, 1.);
}